<template>
    <el-drawer :model-value="visible" :title="isEditMode ? '编辑生命周期规则' : '创建生命周期规则'" direction="rtl" size="50%"
        @close="$emit('close')">
        <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="140px" label-position="top">

            <div class="form-section">
                <h3>基础设置</h3>
                <el-form-item label="规则名称" prop="ID">
                    <el-input v-model="form.ID" placeholder="请输入规则的唯一名称"></el-input>
                </el-form-item>

                <el-form-item label="状态" prop="Status">
                    <el-radio-group v-model="form.Status">
                        <el-radio-button value="Enabled">启用</el-radio-button>
                        <el-radio-button value="Disabled">禁用</el-radio-button>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="应用范围" prop="prefix">
                    <el-radio-group v-model="scopeType" @change="handleScopeChange">
                        <el-radio value="all">作用于整个存储桶</el-radio>
                        <el-radio value="prefix">按前缀匹配</el-radio>
                    </el-radio-group>
                    <el-input v-if="scopeType === 'prefix'" v-model="form.Filter.Prefix"
                        placeholder="例如：logs/ 或 images/" class="prefix-input"></el-input>
                </el-form-item>
            </div>

            <div class="form-section">
                <h3>文件执行策略</h3>
                <p class="section-description">对符合范围的文件进行管理，不包含碎片。</p>

                <el-form-item label="当前版本管理">
                    <el-checkbox v-model="enableCurrentVersionExpiration" label="设置当前版本过期策略" size="large" />
                    <div v-if="enableCurrentVersionExpiration" class="action-row">
                        <span>当前版本在</span>
                        <el-input-number v-model="form.Expiration.Days" :min="1" controls-position="right" />
                        <span>天后，执行</span>
                        <!-- 新增：根据是否开启版本控制，显示不同的过期操作 -->
                        <el-select :model-value="currentVersionActionText" disabled
                            :placeholder="currentVersionActionText" style="width: 180px; margin: 0 5px;">
                            <el-option :label="currentVersionActionText" :value="currentVersionActionText"></el-option>
                        </el-select>
                        <span>操作。</span>
                    </div>
                </el-form-item>

                <el-form-item v-if="isVersioningEnabled" label="历史版本管理">
                    <el-checkbox v-model="enableNoncurrentVersionExpiration" label="设置历史版本过期策略" size="large" />
                    <div v-if="enableNoncurrentVersionExpiration" class="action-row">
                        <span>历史版本在</span>
                        <el-input-number v-model="form.NoncurrentVersionExpiration.NoncurrentDays" :min="1"
                            controls-position="right" />
                        <span>天后，执行</span>
                        <el-select model-value="永久删除(不可恢复)" disabled placeholder="永久删除(不可恢复)"
                            style="width: 180px; margin: 0 5px;">
                            <el-option label="永久删除(不可恢复)" value="永久删除(不可恢复)"></el-option>
                        </el-select>
                        <span>操作。</span>
                    </div>
                </el-form-item>
            </div>

            <div class="form-section">
                <h3>碎片执行策略</h3>
                <p class="section-description">对符合范围的、未完成的分片上传任务进行管理。</p>
                <el-form-item>
                    <el-checkbox v-model="enableAbortIncompleteMultipartUpload" label="设置碎片过期策略" size="large" />
                    <div v-if="enableAbortIncompleteMultipartUpload" class="action-row">
                        <span>碎片在启动</span>
                        <el-input-number v-model="form.AbortIncompleteMultipartUpload.DaysAfterInitiation" :min="1"
                            controls-position="right" />
                        <span>天后，执行</span>
                        <el-select model-value="系统自动删除" disabled placeholder="系统自动删除"
                            style="width: 180px; margin: 0 5px;">
                            <el-option label="系统自动删除" value="系统自动删除"></el-option>
                        </el-select>
                        <span>操作。</span>
                    </div>
                </el-form-item>
            </div>
        </el-form>

        <template #footer>
            <div style="flex: auto">
                <el-button @click="$emit('close')">取消</el-button>
                <el-button type="primary" @click="submitForm" :loading="isSubmitting">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup>
import { ref, watch, computed, reactive } from 'vue';
import apiClient from '@/api';
import { ElMessage } from 'element-plus';

const props = defineProps({
    visible: Boolean,
    bucketName: String,
    isVersioningEnabled: Boolean,
    ruleToEdit: Object,
});

const emit = defineEmits(['close', 'success']);

const ruleFormRef = ref(null);
const isSubmitting = ref(false);
const scopeType = ref('all');

const form = reactive({
    ID: '',
    Status: 'Enabled',
    Filter: {
        Prefix: ''
    },
    Expiration: { Days: 30 },
    NoncurrentVersionExpiration: { NoncurrentDays: 30 },
    AbortIncompleteMultipartUpload: { DaysAfterInitiation: 7 },
});

const enableCurrentVersionExpiration = ref(false);
const enableNoncurrentVersionExpiration = ref(false);
const enableAbortIncompleteMultipartUpload = ref(false);

const isEditMode = computed(() => !!props.ruleToEdit);

const currentVersionActionText = computed(() => {
    return props.isVersioningEnabled ? '创建删除标记' : '永久删除(不可恢复)';
});

const resetForm = () => {
    // 这个函数现在只负责重置数据，不再设置默认ID
    ruleFormRef.value?.resetFields();
    Object.assign(form, {
        ID: '',
        Status: 'Enabled',
        Filter: { Prefix: '' },
        Expiration: { Days: 30 },
        NoncurrentVersionExpiration: { NoncurrentDays: 30 },
    });
    scopeType.value = 'all';
    enableCurrentVersionExpiration.value = false;
    enableNoncurrentVersionExpiration.value = false;
}

// ... (handleScopeChange, rules, submitForm 等函数保持不变) ...

const handleScopeChange = () => {
    if (scopeType.value === 'all') {
        form.Filter.Prefix = '';
    }
}

const rules = {
    ID: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }],
};

const submitForm = async () => {
    if (!ruleFormRef.value) return;
    await ruleFormRef.value.validate(async (valid) => {
        if (valid) {
            isSubmitting.value = true;
            try {
                const newRule = {
                    ID: form.ID,
                    Status: form.Status,
                    Filter: scopeType.value === 'prefix' && form.Filter.Prefix ? { Prefix: form.Filter.Prefix } : {}
                };

                if (enableCurrentVersionExpiration.value) {
                    newRule.Expiration = { Days: form.Expiration.Days };
                }
                if (props.isVersioningEnabled && enableNoncurrentVersionExpiration.value) {
                    newRule.NoncurrentVersionExpiration = { NoncurrentDays: form.NoncurrentVersionExpiration.NoncurrentDays };
                }

                if (enableAbortIncompleteMultipartUpload.value) {
                    newRule.AbortIncompleteMultipartUpload = {
                        DaysAfterInitiation: form.AbortIncompleteMultipartUpload.DaysAfterInitiation
                    };
                }

                if (!newRule.Expiration && !newRule.NoncurrentVersionExpiration && !newRule.AbortIncompleteMultipartUpload) {
                    ElMessage.error('请至少启用一个执行策略。');
                    isSubmitting.value = false; // 别忘了重置提交状态
                    return;
                }

                const { data: existingRules } = await apiClient.get(`/api/v1/buckets/${props.bucketName}/lifecycle`);

                let updatedRules;
                const editIndex = existingRules.findIndex(r => r.ID === (props.ruleToEdit ? props.ruleToEdit.ID : -1));

                if (isEditMode.value && editIndex !== -1) {
                    // 编辑模式: 替换掉旧的规则
                    existingRules[editIndex] = newRule;
                    updatedRules = existingRules;
                } else {
                    // 新建模式: 添加新规则
                    updatedRules = [...existingRules, newRule];
                }

                await apiClient.put(`/api/v1/buckets/${props.bucketName}/lifecycle`, { rules: updatedRules });

                ElMessage.success(isEditMode.value ? '规则更新成功' : '规则创建成功');
                emit('success');
            } catch (error) {
                console.error('提交规则失败:', error);
                ElMessage.error(error.response?.data?.error || '操作失败');
            } finally {
                isSubmitting.value = false;
            }
        }
    });
};

// 【核心修正】使用更健壮的 watch 逻辑来处理数据填充
watch(() => props.ruleToEdit, (newRule) => {
    // 每次抽屉打开时，都先重置表单到初始状态
    resetForm();

    // 如果 newRule 存在，说明是编辑模式，开始填充数据
    if (newRule) {
        console.log("进入编辑模式，正在填充数据:", JSON.parse(JSON.stringify(newRule)));

        // 1. 填充基础信息
        form.ID = newRule.ID;
        form.Status = newRule.Status;

        // 2. 填充应用范围
        if (newRule.Filter && newRule.Filter.Prefix) {
            scopeType.value = 'prefix';
            form.Filter.Prefix = newRule.Filter.Prefix;
        } else {
            scopeType.value = 'all';
            form.Filter.Prefix = '';
        }

        // 3. 填充当前版本过期策略
        if (newRule.Expiration && newRule.Expiration.Days) {
            enableCurrentVersionExpiration.value = true;
            form.Expiration.Days = newRule.Expiration.Days;
        } else {
            enableCurrentVersionExpiration.value = false;
        }

        // 4. 填充历史版本过期策略
        if (newRule.NoncurrentVersionExpiration && newRule.NoncurrentVersionExpiration.NoncurrentDays) {
            enableNoncurrentVersionExpiration.value = true;
            form.NoncurrentVersionExpiration.NoncurrentDays = newRule.NoncurrentVersionExpiration.NoncurrentDays;
        } else {
            enableNoncurrentVersionExpiration.value = false;
        }

        if (newRule.AbortIncompleteMultipartUpload && newRule.AbortIncompleteMultipartUpload.DaysAfterInitiation) {
            enableAbortIncompleteMultipartUpload.value = true;
            form.AbortIncompleteMultipartUpload.DaysAfterInitiation = newRule.AbortIncompleteMultipartUpload.DaysAfterInitiation;
        } else {
            enableAbortIncompleteMultipartUpload.value = false;
        }
    } else {
        // 如果是新建模式，确保ID是唯一的
        form.ID = `rule-${Date.now()}`;
    }
}, { immediate: true }); // immediate: true 保证组件初次加载时也能执行一次

</script>

<style scoped>
.form-section {
    border: 1px solid #dcdfe6;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
}

.form-section h3 {
    margin-top: 0;
    margin-bottom: 20px;
    font-size: 16px;
}

.prefix-input {
    margin-top: 10px;
}

.section-description {
    color: #909399;
    font-size: 14px;
    margin-bottom: 15px;
}

.action-row {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-top: 10px;
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
}
</style>